from typing import Any, List

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.core.security import get_current_active_user, is_admin
from app.crud.api_config import api_config
from app.db.session import get_db
from app.models.user import SysUsers
from app.schemas.api_config import ApiConfig, ApiConfigCreate, ApiConfigUpdate
from app.utils.decorators import api_response
from app.utils.response import error_response, pagination_response

router = APIRouter()


@router.get("/api-configs")
@api_response
async def read_api_configs(
    db: Session = Depends(get_db),
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(100, description="返回的记录数"),
    code: str = Query(None, description="配置代码（支持模糊查询）"),
    api_url: str = Query(None, description="API地址（支持模糊查询）"),
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    获取所有API配置列表
    """
    configs = api_config.get_multi(
        db, 
        skip=skip, 
        limit=limit,
        code=code,
        api_url=api_url
    )
    total = api_config.count(
        db,
        code=code,
        api_url=api_url
    )
    return pagination_response(data=configs, total=total)


@router.post("/api-configs")
@api_response
async def create_api_config(
    *,
    db: Session = Depends(get_db),
    config_in: ApiConfigCreate,
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    创建新API配置（需要管理员权限）
    """
    try:
        # 设置创建人信息
        created_by = current_user.user_name if current_user else None
        config_obj = api_config.create(db, obj_in=config_in, created_by=created_by)
        return config_obj
    except ValueError as e:
        return error_response(
            code=400,
            message=str(e)
        )


@router.get("/api-configs/{config_id}")
@api_response
async def read_api_config(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    根据ID获取API配置信息
    """
    config_obj = api_config.get(db, id=config_id)
    if not config_obj:
        return error_response(
            code=404,
            message="API配置不存在"
        )
    return config_obj


@router.put("/api-configs/{config_id}")
@api_response
async def update_api_config(
    *,
    db: Session = Depends(get_db),
    config_id: int,
    config_in: ApiConfigUpdate,
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    更新API配置（需要管理员权限）
    """
    config_obj = api_config.get(db, id=config_id)
    if not config_obj:
        return error_response(
            code=404,
            message="API配置不存在"
        )
    
    try:
        # 设置更新人信息
        updated_by = current_user.user_name if current_user else None
        config_obj = api_config.update(db, db_obj=config_obj, obj_in=config_in, updated_by=updated_by)
        return config_obj
    except ValueError as e:
        return error_response(
            code=400,
            message=str(e)
        )


@router.delete("/api-configs/{config_id}")
@api_response
async def delete_api_config(
    *,
    db: Session = Depends(get_db),
    config_id: int,
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    删除API配置（需要管理员权限）
    """
    config_obj = api_config.get(db, id=config_id)
    if not config_obj:
        return error_response(
            code=404,
            message="API配置不存在"
        )
    config_obj = api_config.remove(db, id=config_id)
    return config_obj